import requests
import pymysql
import json

#
# 获取所有的屏蔽词
def get_index1(url):
    try:
        headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUm9sZXMiOlsiMTYiXSwiUm9sZUlEcyI6WyLlvIDlj5HkurrlkZgiXSwiSXNBZG1pbiI6ZmFsc2UsIk1hcnQiOiIiLCJFeHBpcnlEYXRlVGltZSI6IjIwMjEtMDgtMzBUMTg6MTk6MTUuMDk3MjAwNCswODowMCJ9.4uNQykhdxqxn1GAcbOZeAFT0yCksFV-hnjlnJkz6Ncc',
            'Cookie': 'Admin-Token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOjEyNiwiVXNlck5hbWUiOiJ6aGFuZ2hvbmciLCJOYW1lIjoi5byg5rSqIiwiUm9sZXMiOlsiMTYiXSwiUm9sZUlEcyI6WyLlvIDlj5HkurrlkZgiXSwiSXNBZG1pbiI6ZmFsc2UsIk1hcnQiOiIiLCJFeHBpcnlEYXRlVGltZSI6IjIwMjEtMDgtMzBUMTg6MTk6MTUuMDk3MjAwNCswODowMCJ9.4uNQykhdxqxn1GAcbOZeAFT0yCksFV-hnjlnJkz6Ncc',
            'Host': 'htgl.cwoqu.com',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36',
            # 'accept-encoding': 'gzip, deflate, br',
            }
        response = requests.get(url, headers=headers, timeout=29)
        response.encoding = "utf-8"
        if response.status_code == 200:
            return response.text
    except Exception as e:
        print('获取网页数据异常：'+str(e))
        return None


def addDB(jsonss):
    # 打开数据库连接，不指定数据库
    conn = pymysql.connect('localhost', 'root', '123456')
    conn.select_db('aweiliao')
    cur = conn.cursor()  # 获取游标

    try:
        # print(jsonss)
        jsonStr = json.loads(jsonss)
        for item in jsonStr['Data']['rows']:
            # 这部分可以循环执行
            sql = "insert into sys_forbidword (keyword,typeid,status) values('{}','{}','{}')".format(
                item["keyword"], item["type"], item["status"]
            )
            print(len(sql))
            insert = cur.execute(sql)
            conn.commit()
            print('添加语句受影响的行数：', insert)
    finally:
        cur.close()
        conn.close()
        print('sql执行成功')

def getData():
    for i in range(1, 148):
        # http://htgl.cwoqu.com/api/basic/forbidlist?page=1&size=20
        print("========================================= 开始获取数据 =================================================")
        print("                                          循环次数："+str(i)+"                                          ")
        print("========================================= 开始获取数据 =================================================")
        addDB(get_index1("http://htgl.cwoqu.com/api/basic/forbidlist?page="+str(i)+"&size=20"))


if __name__ == '__main__':
    getData()